import hashlib
import json
from typing import List


def merge_files(chunk_file: str, source: str, out_file: str):
    """合并文件"""
    sha1_file: str = f"{source}/sha1.txt"
    out = open(out_file, 'wb')

    with open(f"{source}/{chunk_file}", 'r') as f:
        chunks: List[dict] = json.load(f)
        chunks.sort(key=lambda x: x['sort'])

        for chunk in chunks:
            chunk_sha1: str = chunk["chunk_sha1"]
            chunk_path: str = chunk["chunk_path"]

            print(f"正在验证分片: {chunk_path}")
            with open(chunk_path, 'rb') as chunk_f:
                content = chunk_f.read()
                chunk_sha1_new: str = hashlib.sha1(content).hexdigest()
                if chunk_sha1 != chunk_sha1_new:
                    print(f"警告: 分片 {chunk_path} 验证失败")
                    raise ValueError(f"分片验证失败:{chunk_path}")
                out.write(content)
    out.close()
    with open(sha1_file, 'r') as f:
        out = open(out_file, 'rb')
        sha1: str = hashlib.sha1(out.read()).hexdigest()
        original_sha1 = f.readline()
        if sha1 != original_sha1:
            print(f"警告: 文件 {out_file} 验证失败")
            raise ValueError(f"文件验证失败:{out_file}")
        else:
            print(f"文件 {out_file} 验证成功")
        out.close()


if __name__ == '__main__':
    files: List[dict] = [
        {
            "source": "chinese",
            "out_file": "zh_core_web_sm-3.8.0-py3-none-any.whl",
            "chunk_file": "chunk.json"
        },
        {
            "source": "english",
            "out_file": "en_core_web_sm-3.8.0-py3-none-any.whl",
            "chunk_file": "chunk.json"
        }
    ]

    for file in files:
        chunk_file: str = file["chunk_file"]
        source: str = file["source"]
        out_file: str = file["out_file"]
        merge_files(chunk_file, source, out_file)
